package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"zk1/api/request"
	"zk1/internal/dao"
	"zk1/internal/model"
	"zk1/pkg"
)

func RegisterReq(c *gin.Context) {
	var req request.UserRegisterReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	user := model.Users{
		Name:     req.Name,
		Password: req.Password,
	}
	if !dao.CreateUser(&user) {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "添加失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": user,
	})
}
func LoginReq(c *gin.Context) {
	var req request.UserLoginReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	user := dao.GetUserMobile(req.Name)
	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "用户未注册 不能登录",
			"data": nil,
		})
		return
	}
	user = dao.GetUserMobileAndPassword(req.Name, req.Password)
	token, _ := pkg.NewJWT("2210a").CreateToken(pkg.CustomClaims{
		ID: uint(user.Id),
	})
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": token,
	})
}
